package com.omenkk.juc.c1;

import lombok.extern.slf4j.Slf4j;

/**
 * 抛出 InterruptedException 后，JVM 会自动清除中断标志位（重置为 false）。
 */
@Slf4j
public class demo1 {
    public static void main(String[] args) throws InterruptedException{
test2();
    }
    //打断睡眠的线程
    private static void test1() throws InterruptedException{
        Thread t1=new Thread(()->{
            log.debug("sleep...");
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                //throw new RuntimeException(e);
                e.printStackTrace();
            }
        },"t1");
        t1.start();
        Thread.sleep(1000);
        log.debug("interrupt");
        t1.interrupt();
        //如果此刻抛出了异常
        log.debug("打断标记:{}",t1.isInterrupted());
    }
//打断正在运行的线程，不会强制终止线程
    private static void test2() throws InterruptedException{
        Thread t1=new Thread(()->{
            while(true){
                boolean interrupted = Thread.currentThread().isInterrupted();
                if(interrupted){
                   log.debug("被interrupt打断,打断标记为真，退出循环");
                   break;
               }
            }
        },"t1");
        t1.start();
        Thread.sleep(1000);
        log.debug("interrupt");
        Thread.sleep(2000);
        t1.interrupt();
        //如果此刻抛出了异常
        log.debug("打断标记:{}",t1.isInterrupted());
    }

}
